<!--
 * @Description: 第三十五章（event loop 和 nextTick）
 * @Author: IA ia@kepro.space
 * @Date: 2025-02-22 20:29:35
-->
<template>

  <div>
    <h1>第三十五章（event loop 和 nextTick） nextTick）</h1>
    <div>
      <h2>nextTick</h2>
      <div >
        <div class="wraps" ref="box">
          <div>
            <div class="item" v-for="item in chatList">
            <div>{{ item.name }} ：</div>
            <div>{{ item.message }}</div>
          </div>
          </div>
        </div>
        <div class="ipt">
          <div>
            <textarea v-model="ipt" type="text" style="width:100%" />
          </div>
          <div>
            <el-button @click="send" type="primary">send</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>

</template>
<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue';
let chatList = reactive([
  {
    name: '张三',
    message: "xxxxxxxx"
  }
])

let box = ref<HTMLDivElement>()

let ipt = ref('')

// VUE 更新DOM 是异步的，数据更新是同步的
// 我们本次执行的代码是同步的
// 当我们操作DOM时发现数据读取的是上次的，就需要使用nextTick
const send = async () => {
  chatList.push(
    {
      name: 'IA',
      message: ipt.value
    }
  )

  // 1.回调函数的模式
  // nextTick(() => {
  //   box.value!.scrollTop = 999999
  // })
  // 2.async await 写法
  // 在await下面的代码都是异步的
  await nextTick()
  box.value!.scrollTop = 999999
  // ipt.value = ""

}

</script>
<style scoped lang="less">

  .wraps {
    margin: 10px auto;
    width:500px;
    height: 400px;
    overflow: auto;
    overflow-x: hidden;
    background-color: #fff;
    border: 1px solid #ccc;

    .item {
      width: 100%;
      height:50px;
      background-color: #ccc;
      display: flex;
      align-items: center;
      padding: 0 10px;
      border-bottom: 1px solid #fff;
    }

  }

  .ipt {
    margin: 10px auto;
    width:500px;
    height: 50px;
    padding: 0 10px;
    border: 1px solid #ccc;
  }


</style>
